import { fileURLToPath } from 'url';
import path, { dirname } from 'path';
import fs from 'fs';
import { exec } from 'child_process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const signPath = path.join(__dirname, "../myapp.key");
process.env.TAURI_SIGNING_PRIVATE_KEY = signPath;
process.env.TAURI_SIGNING_PRIVATE_KEY_PASSWORD="email";

// 读取 package.json 文件
const packageJsonPath = path.join(__dirname, "../package.json");
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
const tauriJsonPath = path.join(__dirname, "../src-tauri/tauri.conf.json");
const tauriJson = JSON.parse(fs.readFileSync(tauriJsonPath, "utf8"));

const cwd = path.resolve(__dirname, "../");

const execCommand = (command) => {
  return new Promise((resolve, reject) => {
    const commandProcess = exec(
      command,
      {
        cwd,
      },
      (err, stdout, stderr) => {
        if (err) {
          console.error(
            `执行命令 "${command}" 时出错: ${JSON.stringify(err)} ${stderr}`
          );
          reject(err);
          return;
        }
        resolve(stdout);
      }
    );
    // 监听输出
    commandProcess.stdout.on("data", (data) => {
      process.stdout.write(data);
    });

    commandProcess.stderr.on("data", (data) => {
      process.stderr.write(data);
    });
  });
}

const getNextVersion = () => {
    // 获取当前版本号
    const versionParts = packageJson.version.split('.');
    const major = parseInt(versionParts[0], 10);
    const minor = parseInt(versionParts[1], 10);
    const patch = parseInt(versionParts[2], 10);
    return `${major}.${minor}.${patch + 1}`;
}
let startTime = "";
/**
 * 更新版本号
 */
async function updateVersion() {
    // 记录开始时间
    startTime = process.hrtime();
    const newVersion = getNextVersion();
  // 更新 package.json 中的版本号
    try {
      packageJson.version = newVersion;
      fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));

      tauriJson.version = newVersion;
      fs.writeFileSync(tauriJsonPath, JSON.stringify(tauriJson, null, 2));

      console.log( `版本号已更新为 ${newVersion}`);
      buildProject();
    } catch (error) {
      console.error(`更新版本号时出错: ${error.message}`);
    }
}

/**
 * 打包
 */
async function buildProject() {
  console.log(`正在进行打包...`);

  const promiseList = [
    execCommand("npm run build:destop"),
  ];

  try {
    await Promise.all(promiseList);

    // 记录结束时间
    const endTime = process.hrtime(startTime);
    // 计算花费的时间（以秒为单位）
    const elapsedTimeInSeconds = parseInt(endTime[0] + endTime[1] / 1e9);

    console.log(
      ` 打包已完成，输出的文件在dist目录，共耗时${elapsedTimeInSeconds}s，感谢使用`
    );
  } catch (error) {
    console.error(`打包过程中出错: ${error.message}`);
  }
}

updateVersion();